<template>
  <div class="container">
    <el-row class="header">
      <el-col class="asd" :span="14" align="left">
        <el-input
          clearable
          icon="el-icon-search"
          v-model="data.params.projectName"
          placeholder="项目名称"
          style="width: 220px; margin-right: 15px"
        />
        <el-button class="ordinary" @click="search()">搜索</el-button>
      </el-col>
      <el-col class="asd" :span="10" align="right">
        <el-button v-limit="'XMZX:SCYS:GCSC:EXPORT'" class="ordinary" @click="exportExcel()"
          >批量导出</el-button
        >
        <el-button v-limit="'XMZX:SCYS:GCSC:ADD'" type="primary" @click="handleExamineAdd()"
          >新增审查</el-button
        >
      </el-col>
    </el-row>

    <Table
      :loading="data.isLoading"
      :tableArr="data.allTableData"
      :columns="data.columns"
      :page-size="data.params.size"
      :page-num="data.params.current"
      @selectList="getCurrentList"
      @row-click="handleRowClick"
    >
      <template #status>
        <el-table-column label="验收状态" width="80">
          <template #default="{ row }">
            <span class="draft" v-if="row.status == 0">待上报</span>
            <span class="pending" v-if="row.status == 1">待审批</span>
            <span class="approved" v-if="row.status == 2">正常办结</span>
            <span class="rejection" v-if="row.status == 3">已退回</span>
            <span class="rejection" v-if="row.status == 4">已撤办</span>
            <span class="rejection" v-if="row.status == 5">强制办结</span>
            <span class="rejection" v-if="row.status == 6">已废弃</span>
            <span class="rejection" v-if="row.status == 7">已挂起</span>
            <span class="rejection" v-if="row.status == 8">已驳回</span>
          </template>
        </el-table-column>
      </template>
      <template #operate="{ row }">
        <el-button
          v-limit="'XMZX:SCYS:GCSC:ESCALATION'"
          v-if="row.status == 0 && data.usercname == row.projectLeader"
          @click="handleExamineReport(row)"
          type="primary"
          >上报</el-button
        >
        <el-button
          v-limit="'XMZX:SCYS:GCSC:ESCADETAIL'"
          v-if="row.status != 0"
          class="ordinary"
          @click="handleDetail(row)"
          >上报详情</el-button
        >
        <el-button
          v-limit="'XMZX:SCYS:GCSC:EXAMDETAIL'"
          v-if="row.status == 0"
          class="ordinary"
          @click="handleExamineDetail(row)"
          >审查详情</el-button
        >
        <el-button
          v-if="row.status == 1 && row.currUserId?.split(',').includes(data.username)"
          v-limit="'XMZX:SCYS:GCSC:EXAMINE'"
          type="primary"
          @click="handleExamine(row)"
          >审批</el-button
        >
      </template>
    </Table>
    <div class="example-pagination-block">
      <el-pagination
        background
        layout="prev, pager, next ,total,sizes,jumper"
        :total="data.total"
        :page-size="data.params.size"
        v-model:current-page="data.params.current"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
    <!-- 新增审查-->
    <el-dialog v-model="data.doExamineDialog" width="60%" :title="data.examineProcess">
      <Examine
        ref="examineRef"
        :examineProcess="data.examineProcess"
        v-if="data.doExamineDialog"
      ></Examine>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeExamine">关闭</el-button>
          <el-button
            v-if="data.examineProcess == '选择审查项目'"
            type="primary"
            @click="nextExamine"
            >下一步</el-button
          >
          <el-button
            v-if="data.examineProcess == '审查下发'"
            type="primary"
            @click="doExamineSave()"
            >确认下发</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 审查上报申请 -->
    <!-- <el-dialog v-model="data.editDialog" width="60%" :title="data.currentHandle">
      <Information
        :title="data.currentHandle"
        ref="reportRef"
        v-if="data.editDialog"
      ></Information>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.editDialog = false">关闭</el-button>
          <el-button
            v-if="data.currentHandle == '项目过程审查上报'"
            type="primary"
            @click="handleSaveChange()"
            >保存</el-button
          >
        </span>
      </template>
    </el-dialog> -->
    <!-- 审查上报流程与表单 -->
    <el-dialog
      v-model="data.editDialog"
      width="60%"
      :title="data.currentHandle"
      @close="handleClose"
    >
      <el-tabs v-model="activeName" class="demo-tabs box">
        <el-tab-pane label="基本信息" name="1">
          <Information
            :title="data.currentHandle"
            ref="reportRef"
            v-if="data.editDialog"
          ></Information>
        </el-tab-pane>
        <el-tab-pane
          label="流程图"
          name="2"
          v-if="data.currentHandle != '审查上报申请' && data.currentRow.status != 0"
        >
          <ExpertOpinion
            v-if="data?.currentRow.projectCategory == 2 && data.editDialog"
            ref="expertOpinionRef"
            :initData="data.currentRow.details?data.currentRow.details:[]"
            :title="data.currentHandle"
          ></ExpertOpinion>
          <hr />
          <flowChart v-if="data.editDialog" :processInstanceId="data.processInstanceId"></flowChart>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer" style="float: left" v-if="data.currentHandle == '审查上报审批'">
          <el-form label-width="120px" :rules="rules" ref="ruleFormRef" :model="ruleForm">
            <el-form-item label="审批意见" prop="comment">
              <el-input
                type="textarea"
                placeholder="审批意见"
                v-model="ruleForm.comment"
                style="width: 450px; margin-top: -10px"
                clearable
              />
            </el-form-item>
          </el-form>
        </div>
        <span class="dialog-footer">
          <el-button @click="data.editDialog = false">关闭</el-button>
          <el-button
            v-if="data.currentHandle == '审查上报申请'"
            type="primary"
            @click="handleSaveChange()"
            >提交</el-button
          >
          <el-button
            v-if="data.currentHandle == '审查上报审批'"
            type="danger"
            @click="handleNoPass()"
            >审批驳回</el-button
          >
          <el-button
            v-if="data.currentHandle == '审查上报审批'"
            type="primary"
            @click="handlePass()"
            >审批通过</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 审查详情 -->
    <el-dialog v-model="data.editDialog2" width="50%" title="审查详情">
      <ExaminDetail v-if="data.editDialog2"></ExaminDetail>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.editDialog2 = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 导出字段选择 -->
    <Export
      :detailList="data.detailList"
      :showing="data.exportDialog"
      @close="closeExport"
      @handle-filed="handleFiled"
    ></Export>
    <el-dialog
      v-model="data.dealVisible"
      title="系统正在处理中....."
      width="40%"
      top="14%"
      height="400"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <el-alert
        type="success"
        :closable="false"
        style="margin-bottom: 20px"
        description="当前流程正在处理中,请稍等……"
      >
      </el-alert>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { reactive, ref } from 'vue'
import tableData from './tableHeader.json'
import Information from './components/information.vue'
import ExaminDetail from './components/examine-detail.vue'
import ExpertOpinion from './components/expert-opinion.vue'
import Examine from './components/examine.vue'
import flowChart from '@/components/PublicProcess/Chart/flowChart.vue'
import Export from '@/views/project/components/Export/index.vue'
import {
  getProductList,
  getExportExcel,
  getDetail,
  getExamineDetail,
  examineReportSave,
  examineSave,
  saveToDeal,
  dealedReport,
  acceptanceProjects,
} from '../../api/examine'
import Table from '../../components/table2/table.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useStore } from 'vuex'
import { startProcess, allowProcess, refuseProcess } from '../../api/commom'
import { servicesLoading } from '@/utils/loading'

export default {
  components: {
    Table,
    Information,
    Examine,
    ExaminDetail,
    ExpertOpinion,
    flowChart,
    Export,
  },
  setup() {
    const store = useStore()
    const examineRef = ref()
    const reportRef = ref()
    const activeName = ref('1')
    let data = reactive({
      examineProcess: '选择审查项目',
      currentHandle: '',
      params: {
        current: 1,
        size: 10,
        projectName: '',
      },
      total: 0,
      isLoading: false,
      allTableData: [],
      columns: tableData.platformTableHeader,
      ids: [],
      processInstanceId: '',
      currentRow: {} as any,
      currentList: [] as any,
      editDialog: false,
      editDialog2: false,
      doExamineDialog: false,
      dealVisible: false,
      exportDialog: false,
      detailList: [] as any,
      usercname: JSON.parse(localStorage.getItem('userInfo') as any).cname,
      username: JSON.parse(localStorage.getItem('userInfo') as any).username,
    })
    const ruleFormRef = ref()
    const ruleForm = reactive({
      comment: '',
    })
    const rules = reactive({
      comment: [{ required: true, message: '请输入审批意见', trigger: 'change' }],
    })
    const search = () => {
      data.params.current = 1
      onSearch()
    }
    const onSearch = () => {
      data.isLoading = true
      getProductList(data.params).then((res) => {
        if (res.data.code == 200) {
          let result = res.data.data
          result.records.map((item) => {
            item.releaseTime = item.releaseTime?.slice(0, 10)
            item.startTime = item.startTime?.slice(0, 10)
            item.endTime = item.endTime?.slice(0, 10)
          })
          data.allTableData = result.records
          data.total = result.total
          data.isLoading = false
        }
      })
    }
    onSearch()
    const getCurrentList = (currentList) => {
      console.log(currentList, 'currentList')
      data.currentList = currentList
      data.ids = currentList.map((item) => {
        return item.id
      })
    }
    //改变页码
    const handleCurrentChange = (e) => {
      console.log(e, 'handleCurrentChange')
      data.params.current = e
      onSearch()
    }
    //改变页数限制
    const handleSizeChange = (e) => {
      console.log(e, 'handleSizeChange')
      data.params.size = e
      data.params.current = 1
      onSearch()
    }
    const closeExamine = () => {
      data.doExamineDialog = false
      data.examineProcess = '选择审查项目'
      console.log(data.examineProcess, 'data.examineProcess')
    }
    const nextExamine = () => {
      examineRef.value.hasChoose().then((res) => {
        if (res) {
          data.examineProcess = '审查下发'
        } else {
          ElMessage({
            message: '请至少选择一个项目',
            type: 'warning',
          })
        }
        console.log(data.examineProcess, 'data.examineProcess')
      })
    }
    const doExamineSave = () => {
      examineRef.value.getExamineParams().then((params) => {
        console.log(params, 'getExamineParams')
        examineSave(params).then((res) => {
          ElMessage({
            message: '新增成功',
            type: 'success',
          })
          onSearch()
          data.doExamineDialog = false
          data.examineProcess = '选择审查项目'
          console.log(res, 'res')
          let result = res.data.data.map((item) => {
            return {
              projectLeader: item.projectLeader,
              businessId: item.id,
            }
          })
          console.log(result, 'result')
          saveToDeal(result).then((res) => {
            console.log(res, 'res')
            ElMessage({
              message: '已生成代办',
              type: 'success',
            })
          })
        })
      })
    }

    const handleSaveChange = () => {
      reportRef.value.submitForm().then(() => {
        ElMessageBox.confirm('确认上报审查并提交申请吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          store.state.projectCenter.reportDetailForm.releaseId = (data.currentRow as any).id
          examineReportSave(store.state.projectCenter.reportDetailForm).then((res) => {
            if (res.data.code == 200) {
              data.editDialog = false
              dealedReport(data.currentRow.id).then((res) => {
                console.log(res, 'dealedReport')
                // getTableList()
              })
              const loading = servicesLoading({ fullscreen: true })
              startProcess({
                flowKey: 'Process-Review',
                businessKey: data.currentRow.id,
                businessType: 'YW08',
                random: new Date().valueOf(),
              })
                .then((res) => {
                  loading.close()
                  if (res.data.code != 200) {
                    ElMessage({
                      message: '流程启动失败,请稍后重试',
                      type: 'warning',
                    })
                  } else {
                    data.dealVisible = true
                    deal(data.currentRow.id, 1)
                  }
                })
                .catch(() => {
                  loading.close()
                })
              onSearch()
            }
          })
        })
      })
    }

    const handleExamineDetail = (row) => {
      examineDetailData(String(row.id))
      data.currentRow = row
      store.commit('projectCenter/getRowId', row.id)
    }
    const handleExamineReport = (row) => {
      data.editDialog = true
      data.currentRow = row
      data.currentHandle = '审查上报申请'
      // 清除form表单的值
      store.commit('projectCenter/emptyReportDetailForm')
      store.commit('projectCenter/getRowId', row.id)
    }
    let examineDetailForm = reactive(store.state.projectCenter.examineDetailForm)
    //详情数据获取
    const examineDetailData = async (id) => {
      let res = await getExamineDetail(id)
      data.editDialog2 = true
      if (res.data.success) {
        for (let key in examineDetailForm) {
          examineDetailForm[key] = res.data.data?.[key]
        }
      }
    }

    const closeExport = () => {
      data.exportDialog = false
    }
    const handleFiled = (arr) => {
      console.log(arr, 'handleFiled')
      if (arr.length > 0) {
        ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          getExportExcel({ ...data.params, ids: data.ids, headList: arr })
          console.log('批量导出')
          data.exportDialog = false
        })
      }
    }
    const exportExcel = () => {
      data.exportDialog = true
      data.detailList = [
        { fieldName: 'projectName', title: '项目名称' },
        { fieldName: 'projectId', title: '项目编号' },
        { fieldName: 'projectType', title: '项目类型' },
        { fieldName: 'startTime', title: '项目开始时间' },
        { fieldName: 'endTime', title: '项目截止时间' },
        { fieldName: 'projectLeader', title: '项目负责人' },
        { fieldName: 'projectContacts', title: '项目联系人' },
        { fieldName: 'releaseTime', title: '下达时间' },
      ]
    }
    // const exportExcel = () => {
    //   ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
    //     confirmButtonText: '确认',
    //     cancelButtonText: '取消',
    //     type: 'warning',
    //   }).then(() => {
    //     getExportExcel(data.params.projectName, data.ids)
    //   })
    // }
    const handleRowClick = (row) => {
      if (row.status == 0) {
        handleExamineDetail(row)
      } else {
        handleDetail(row)
      }
    }
    const handleDetail = (row) => {
      data.currentHandle = '审查上报详情'
      detailData(row.id)
      data.currentRow = row
      store.commit('projectCenter/getRowId', row.id)
    }
    //详情数据获取
    const detailData = async (id) => {
      const loading = servicesLoading({ fullscreen: false })
      let res = await getDetail(id)
      console.log(res.data, 'res.data')
      if (res.data.success) {
        const resData = res.data.data
        store.commit('projectCenter/getReportDetailForm', { ...res.data.data })
        data.editDialog = true
        data.processInstanceId = resData.processInstanceId
        loading.close()
      }
    }
    //审查审批流程
    const handleExamine = (row) => {
      data.currentHandle = '审查上报审批'
      data.currentRow = row
      //获取对应流程processInstanceId,渲染流程图
      detailData(row.id)
    }
    const handleExamineAdd = () => {
      data.doExamineDialog = true
      store.commit('projectCenter/emptyExamineDetailForm')
    }
    const expertOpinionRef = ref()
    //审批通过
    const handlePass = () => {
      ruleFormRef.value.validate((valid) => {
        if (valid) {
          if(!expertOpinionRef.value.verifyOpinionList()){
            return
          }
          ElMessageBox.confirm('确认通过本次申请吗？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            handleResult(allowProcess, 2)
            let opinionList = expertOpinionRef.value.getOpinionList()
            opinionList.forEach(item => {
              item.projectId = data.currentRow.id
            });
            acceptanceProjects([
              {
                id: data.currentRow.id,
                approvalOpinion: '审批通过',
                approvalFileName: '',
                approvalFilePath: '',
                details: opinionList,
              },
            ]).then(res=>{
              console.log(res,'acceptanceProjects');
            })
          })
        }
      })
    }
    const handleNoPass = () => {
      ruleFormRef.value.validate((valid) => {
        if (valid) {
          ElMessageBox.confirm('确认驳回本次申请吗？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            handleResult(refuseProcess, 8)
            let opinionList = expertOpinionRef.value.getOpinionList()
            opinionList.forEach(item => {
              item.projectId = data.currentRow.id
            });
            acceptanceProjects([
              {
                id: data.currentRow.id,
                approvalOpinion: '审批不通过',
                approvalFileName: '',
                approvalFilePath: '',
                details: opinionList,
              },
            ]).then(res=>{
              console.log(res,'acceptanceProjects');
            })
          })
        }
      })
    }
    const handleResult = (handleProcess, status) => {
      const loading = servicesLoading({ fullscreen: true, text: '正在请求流程' })
      handleProcess({
        procInsId: data.processInstanceId,
        comment: ruleForm.comment,
        flowKey: 'Process-Review',
        businessKey: data.currentRow.id,
        businessType: 'YW08',
        random: new Date().valueOf(),
      })
        .then((res) => {
          loading.close()
          if (res.data.code != 200) {
            ElMessage({
              message: res.data.message,
              type: 'warning',
            })
          } else {
            data.editDialog = false
            data.dealVisible = true
            deal(data.currentRow.id, status)
          }
        })
        .catch(() => {
          loading.close()
        })
    }
    // 处理不通过,提交的过程中.......
    let deal = (id, state) => {
      let times = setInterval(() => {
        getDetail(id).then((res) => {
          const resData = res.data.data
          if (resData.status == state || (state == 2 && resData.status == 1)) {
            data.dealVisible = false
            onSearch()
            ElMessage({
              message: '流程办理成功',
              type: 'success',
            })
            clearTimeout(times)
          }
        })
      }, 3000)
    }
    const handleClose = () => {
      console.log('对话框关闭了')
      data.editDialog = false
      activeName.value = '1'
      if (data.currentHandle == '审查上报审批') {
        ruleFormRef.value.resetFields()
      }
    }
    return {
      data,
      rules,
      ruleForm,
      ruleFormRef,
      examineRef,
      activeName,
      reportRef,
      expertOpinionRef,
      getCurrentList,
      nextExamine,
      closeExamine,
      handleDetail,
      handleRowClick,
      handleCurrentChange,
      handleSizeChange,
      handleExamineDetail,
      handleExamine,
      handleExamineAdd,
      handleExamineReport,
      handleSaveChange,
      doExamineSave,
      exportExcel,
      closeExport,
      handleFiled,
      search,
      handlePass,
      handleNoPass,
      handleClose,
    }
  },
}
</script>

<style lang="scss" scoped>
.container {
  background-color: white;
  padding: 20px;
}
/deep/.el-dialog__body {
  max-height: 500px;
  overflow-y: scroll;
}
</style>
